package com.orgcent.rss;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Stack;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.util.Log;

import com.orgcent.rss.entity.BaseHandler;
import com.orgcent.rss.entity.Channel;
import com.orgcent.rss.entity.Image;
import com.orgcent.rss.entity.Item;
import com.orgcent.util.Tools;

/**
 * 使用SAX方式解析RSS中的xml
 */
public class RSSHandler extends BaseHandler {
	/**
	 * 记录最近的标签
	 */
	private final Stack<String> tagStack = new Stack<String>();
	private final Channel channel = new Channel();
	
	@Override
	public void characters(char[] ch, int start, int length)//获取所有文本
			throws SAXException {
		String chars = new String(ch, start, length).trim();
		if(!"".equals(chars)) {
			setText(chars);  //给对象中的对应属性赋值
		}
	}
	
	/**
	 * 将标签对应的文本信息赋值到对应的对象属性中
	 * @param text
	 */
	private void setText(String text) {
		String tagName = (String)tagStack.peek().toLowerCase();//查看栈顶对象而不移除它 
		int length = tagStack.size();//获取父标签
		String parentTagName = (length > 1) ? tagStack.elementAt(tagStack.size() - 2) : null;
		
		Object objective = null; //根据当前标签的父标签找到对应的对象
		if(Channel.NAME.equalsIgnoreCase(parentTagName)) {
			objective = channel;
		} else if(Item.NAME.equalsIgnoreCase(parentTagName)){
			objective = channel.items.lastElement();
		} else if(Image.NAME.equalsIgnoreCase(parentTagName)) {
			objective = channel.image;
		}
		
		try {
			if(null != objective) {//根据当前标签名称给对应的对象中的属性赋值[标签名==对象属性名]
				Field f = objective.getClass().getDeclaredField(tagName);
				f.setAccessible(true);
				f.set(objective, text);
				f = null;
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public void endDocument() throws SAXException {
		 hash.put(Channel.NAME, channel);//保存入hash，这里保存的是Vector对象
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		tagStack.pop();//移除栈顶对象并作为此函数的值返回该对象
	}

	@Override
	public boolean parse(String xmlString) {
		try {  
            super.parserXml(this, xmlString);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
	}
	
	@Override
	public boolean parseFromURI(String uri) {
		try {  
            super.parserXml(uri, this);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
	}

	@Override
	public void startDocument() throws SAXException {
		channel.items.clear();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if(Item.NAME.equalsIgnoreCase(qName)) { //<item>标签，向channel.items中添加一个新的Item对象
			channel.items.add(new Item());
		}
		tagStack.push(qName);
	}

	public Channel getChannel() {
		return channel;
	}
}
